package cc.customer.authorization.interceptor;


import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cc.customer.authorization.Constants;
import cc.customer.authorization.manager.RedisTokenManager;

/**
 * 自定义授权认证拦截器，判断此次请求是否合法
 * @author Wang
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisTokenManager manager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        String timestamp = request.getHeader("timestamp");
        String signature = request.getHeader("signature");


        //判断这三个是否为空
        if (null == token || null == timestamp || null == signature) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //先获取所有请求参数，包括token, timestamp
        Enumeration<?> parameterNames =  request.getParameterNames();
        Map<String, String> params = new HashMap<String, String>();
        params.put("token", token);
        params.put("timestamp", timestamp);
        while (parameterNames.hasMoreElements()) {
            String parameterName = (String) parameterNames.nextElement();
            String parameterValue = request.getParameter(parameterName);
            params.put(parameterName, parameterValue);
        }


        //然后所有请求参数生成签名然后做对比
       /* if (!signature.equals(manager.createSign(params))) {

            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }*/

        //时间戳对比，时间大于X分钟则判定为请求非法
       /* long mins = (System.currentTimeMillis() - Long.valueOf(timestamp))/1000/60;
        if (mins > Constants.TIMESTAMP_EXPIRES_MINS) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }*/

        //Token是否有效，是否存在redis中
        String userId = manager.checkToken(token);
        if (userId == null || userId.length() == 0) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //如果请求合法，将token对应的用户id存在request中，便于Controller层获取
        request.setAttribute(Constants.CURRENT_USER_ID, userId);
        //如果请求合法，说明此用户进行了一次有效操作，延长 token的过期时间
        manager.expireToken(token);
        return true;

    }

}
